package com.tange.ai.iot.client.gnssa.token

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.tange.ai.iot.client.gnssa.BuildConfig
import com.tange.ai.iot.client.gnssa.Constants
import com.tange.ai.iot.client.gnssa.databinding.ActivityInternalAccountLoginBinding
import com.tange.ai.iot.client.gnssa.home.HomeActivity
import com.tange.ai.iot.client.gnssa.utils.SP
import com.tange.base.toolkit.PreferenceUtil
import com.tange.base.toolkit.onClicked
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.core.access.token.Authentication
import com.tange.core.builtin.account.BuiltinAccount

/**
 * 使用探鸽账号体系，进行登录，以获取用户令牌
 * 详见文档：https://tange-ai.feishu.cn/wiki/wikcn23dyAZIHGz5OGjOxe8l6yD#XMAqdYeKsoaOomx0y98cX7yon4e
 */
class InternalAccountLoginActivity: AppCompatActivity() {

    companion object {
        const val PRE_AREA_CODE = "PRE_AREA_CODE"
        const val PRE_USER_NAME = "PRE_USER_NAME"
        const val PRE_USER_PWD = "PRE_USER_PWD"
        const val PRE_TOKEN = "PRE_TOKEN"
        const val TANGE_TOKEN = "TANGE_TOKEN"
    }

    private lateinit var binding: ActivityInternalAccountLoginBinding

    private var loading: BasicDialogLoading? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityInternalAccountLoginBinding.inflate(layoutInflater).apply {

            setContentView(root)
            supportActionBar?.hide()

            forgot.onClicked {
                startActivity(Intent(this@InternalAccountLoginActivity, InternalAccountForgotActivity::class.java))
            }

            register.onClicked {
                startActivity(Intent(this@InternalAccountLoginActivity, InternalAccountRegisterActivity::class.java))
            }

            login.setOnClickListener {
                loginInternal()
            }
        }

        val customAppId = SP.getString(this@InternalAccountLoginActivity, Constants.KEY_CUSTOM_APP_ID, "")
        val _appId = if (!TextUtils.isEmpty(customAppId)) customAppId else BuildConfig.TG_APP_ID
        binding.accountType.setText("APPID \"${_appId}\" 下的账号：")

        window.apply {
            var uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            uiFlags = uiFlags or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            statusBarColor = Color.TRANSPARENT
            decorView.systemUiVisibility = uiFlags
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        }

        loading = BasicDialogLoading(this).apply {
            setMessage("登录中...")
        }

        com.tange.ai.iot.client.gnssa.utils.Utils.setStatusBar(this, Color.TRANSPARENT)

        val userName = PreferenceUtil.getString(this, PRE_USER_NAME, "")
        val userPwd = PreferenceUtil.getString(this, PRE_USER_PWD, "")
        val areaCode = PreferenceUtil.getString(this, PRE_AREA_CODE, "86")

        if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userPwd)) {
            loading?.dismiss()
            loading?.show()
            binding.areaCode.setText(areaCode)
            binding.username.setText(userName)
            binding.password.setText(userPwd)
            binding.password.postDelayed({
                loginInternal()
            }, 1000)
        }

        binding.username.postDelayed({ binding.username.requestFocus() }, 500)
    }

    override fun onPause() {
        super.onPause()
        loading?.dismiss()
    }

    private fun loginInternal() {

        if (loading?.isShowing != true) {
            loading?.show()
        }

        val areaCode = binding.areaCode.text.toString().trim()
        val account = binding.username.text.toString().trim()
        val pwd = binding.password.text.toString().trim()

        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "用户名或者密码为空", Toast.LENGTH_LONG).show()
            loading?.dismiss()
            return
        }

        val finalAreaCode = if (TextUtils.isEmpty(areaCode)) "86" else areaCode
        BuiltinAccount.login().login(account, pwd, finalAreaCode) {
            loading?.dismiss()
            if (it.success) {
                val token = it.data?.accessToken ?: ""
                if (!TextUtils.isEmpty(token)) {
                    PreferenceUtil.setString(this@InternalAccountLoginActivity, PRE_AREA_CODE, areaCode)
                    PreferenceUtil.setString(this@InternalAccountLoginActivity, PRE_USER_NAME, account)
                    PreferenceUtil.setString(this@InternalAccountLoginActivity, PRE_USER_PWD, pwd)
                    configureToken(token)
                }
            } else {
                Toast.makeText(this, "登录失败: ${it.message}", Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun configureToken(token: String) {

        Authentication.configure(token) {
            if (it.success && it.data != null) {
                startActivity(Intent(this, HomeActivity::class.java))
                binding.username.setText("")
                binding.password.setText("")
            } else {
                Toast.makeText(this, "用户令牌校验失败, code = ${it.code} , msg = ${it.message}", Toast.LENGTH_LONG).show()
            }
        }
    }
}